<template>
    <div class="cyberpunk-container">
        <!-- 连接状态指示器 -->
        <div class="connection-status" :class="{ connected: isConnected }">
            <div class="neon-pulse"></div>
            {{ isConnected ? '🟢 量子连接已建立' : '🔴 连接量子通道...' }}
        </div>

        <div class="cyber-chat">
            <!-- 在线用户列表 -->
            <div class="neon-userlist">
                <h3 class="list-title">🚀 在线特工</h3>
                <div
                    v-for="user in sortedUsers"
                    :key="user.id"
                    @click="selectUser(user)"
                    :class="[
                        'user-card',
                        {
                            active: selectedUser?.id === user.id,
                        },
                    ]"
                >
                    <div class="avatar-frame">
                        <img :src="user.photo" class="hologram-avatar" />
                        <div class="neon-border"></div>
                    </div>
                    <div class="user-info">
                        <span class="agent-name">
                            {{ user.username }}
                            <el-icon v-if="user.id === userStore.id" class="self-icon">
                                <User />
                            </el-icon>
                        </span>
                        <span class="agent-id">ID: {{ user.id }}</span>
                    </div>
                </div>
            </div>

            <!-- 聊天窗口 -->
            <div class="cyber-window" v-if="selectedUser">
                <div class="chat-header">
                    <el-button type="primary" @click="handleBack" class="cyber-button">
                        <el-icon><ArrowLeft /></el-icon>
                        <span>返回大厅</span>
                        <div class="button-glitch"></div>
                    </el-button>
                    <div class="header-glow"></div>
                    <img :src="selectedUser.photo" class="target-avatar" />
                    <h3 class="target-name">{{ selectedUser.username }}</h3>
                </div>

                <div class="matrix-messages">
                    <div
                        v-for="msg in messages"
                        :key="msg.timestamp"
                        :class="['message-bubble', msg.from === userStore.id ? 'sent' : 'received']"
                    >
                        <div class="message-content">{{ msg.content }}</div>
                        <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
                    </div>
                </div>

                <div class="cyber-input">
                    <input
                        v-model="newMessage"
                        @keyup.enter="sendMessage"
                        placeholder="输入加密消息..."
                        class="neon-input"
                    />
                    <button @click="sendMessage" class="glow-button">
                        <span>传输</span>
                        <div class="button-rays"></div>
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useUserStore } from '@/store/user'
import { User, ArrowLeft } from '@element-plus/icons-vue' // 新增图标引入
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const onlineUsers = ref([])
const selectedUser = ref(null)
const messages = ref([])
const newMessage = ref('')
let socket = null
const isConnected = ref(false)

// 添加返回方法
const handleBack = () => {
    selectedUser.value = null
    messages.value = []
    router.push('/main/') // 使用router实例进行跳转
}
// 新增计算属性实现排序
const sortedUsers = computed(() => {
    return onlineUsers.value
        .filter((user) => user.id !== userStore.id) // 过滤掉自己
        .sort((a, b) => a.id - b.id) // 按ID排序（或保持原有排序）
})
watch(
    () => route.params.userId,
    (newVal) => {
        if (newVal) {
            const user = onlineUsers.value.find((u) => u.id === parseInt(newVal))
            if (user) selectUser(user)
        }
    },
    { immediate: true }
)

onMounted(() => {
    // 如果已有全局socket连接，使用现有连接
    if (userStore.socket) {
        console.log('ChatWindow: 使用已存在的WebSocket连接');
        socket = userStore.socket;
        isConnected.value = true;
        
        // 获取当前在线用户
        onlineUsers.value = userStore.onlineUsers;
        
        // 如果route中有userId参数，尝试选择对应用户
        if (route.params.userId) {
            const userId = parseInt(route.params.userId);
            const user = onlineUsers.value.find(u => u.id === userId);
            if (user) {
                selectUser(user);
            }
        }
        
        // 注册消息处理函数
        const originalOnMessage = socket.onmessage;
        socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            
            switch (data.event) {
                case 'online-users':
                    onlineUsers.value = data.users;
                    break;
                case 'private-message':
                    messages.value.push({
                        from: data.from,
                        content: data.content,
                        timestamp: data.timestamp,
                    });
                    break;
                case 'history-message':
                    messages.value = data.messages.map((msg) => ({
                        from: msg.fromUserId,
                        content: msg.content,
                        timestamp: new Date(msg.createTime).getTime(),
                    }));
                    break;
                default:
                    // 对于不处理的消息，调用原始处理函数
                    if (originalOnMessage) originalOnMessage(event);
            }
        };
        
        // 发送ping获取在线用户
        try {
            socket.send(JSON.stringify({event: "ping"}));
        } catch (e) {
            console.error('发送ping消息失败:', e);
        }
    } else {
        console.error('无法获取WebSocket连接');
        isConnected.value = false;
    }
});

const selectUser = (user) => {
    // 新增选择用户方法
    selectedUser.value = user
    // 实际项目应调用API获取历史消息
    messages.value = []
    // 发送获取历史消息的请求
    const historyRequest = {
        event: 'get-history',
        from: userStore.id,
        to: user.id,
    }
    socket.send(JSON.stringify(historyRequest)) // 发送请求到服务器获取历史消息
}

const sendMessage = () => {
    if (newMessage.value.trim() && selectedUser.value) {
        const message = {
            event: 'private-message',
            to: selectedUser.value.id,
            content: newMessage.value,
        }
        socket.send(JSON.stringify(message))
        messages.value.push({
            from: userStore.id,
            content: newMessage.value,
            timestamp: Date.now(),
        })
        newMessage.value = ''
        // 添加滚动逻辑
        nextTick(() => {
            const container = document.querySelector('.matrix-messages')
            if (container) {
                container.scrollTop = container.scrollHeight
            }
        })
    }
}

const formatTime = (timestamp) => {
    return new Date(timestamp).toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
    })
}
watch(messages, () => {
    nextTick(() => {
        const container = document.querySelector('.matrix-messages')
        if (container) container.scrollTop = container.scrollHeight
    })
}) // 监听消息列表的变化，当有新消息时，自动滚动到底部
onUnmounted(() => {
    // 不关闭WebSocket，因为其他组件可能还在使用
    socket = null;
})
</script>

<style scoped>
/* 赛博朋克主题 */
.cyberpunk-container {
    background: #0a0a0a;
    padding: 1rem; /* 减少内边距 */
    position: fixed; /* 改为固定定位 */
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* 连接状态指示 */
.connection-status {
    position: relative;
    color: #0ff;
    font-family: 'Courier New', monospace;
    padding: 1rem;
    background: rgba(0, 255, 255, 0.05);
    border: 1px solid #0ff;
    margin-bottom: 2rem;
    display: flex;
    align-items: center;
    gap: 1rem;
}

.neon-pulse {
    width: 12px;
    height: 12px;
    background: #0ff;
    border-radius: 50%;
    animation: neonPulse 1.5s infinite;
}
.cyber-chat {
    display: flex;
    grid-template-columns: 300px 1fr;
    gap: 0.5rem;
    height: 80vh;
    flex-grow: 1;
    padding: 1rem;
    background: #0a0a0a;
}
/* 用户列表 */
.neon-userlist {
    width: 280px;
    background: linear-gradient(145deg, #1a1a1a 0%, #0a0a0a 100%);
    border: 1px solid #4caf50;
    box-shadow: 0 0 30px rgba(76, 175, 80, 0.2), inset 0 0 15px rgba(76, 175, 80, 0.1);
    padding: 1.5rem;
    border-radius: 8px;
    overflow-y: auto;
    position: relative;
}
/* 分栏分隔线增强 */
.neon-userlist::after {
    content: '';
    position: absolute;
    right: -1px;
    top: 0;
    height: 100%;
    width: 2px;
    background: linear-gradient(180deg, transparent 0%, #4caf50 50%, transparent 100%);
    box-shadow: 0 0 15px #4caf50;
}

.list-title {
    color: #fff;
    text-shadow: 0 0 10px #7028e4;
    margin-bottom: 1.5rem;
}
/* 消息区域自动滚动 */
.matrix-messages {
    flex: 1;
    overflow-y: auto;
    padding: 1.5rem;
    display: flex;
    flex-direction: column;
    gap: 1.2rem;
}

/* 输入框区域固定高度 */
.cyber-input {
    padding: 1.5rem;
    background: rgba(0, 0, 0, 0.3);
    border-top: 1px solid rgba(112, 40, 228, 0.5);
    display: flex;
    gap: 1rem;
    justify-content: flex-end; /* 新增右对齐 */
}
.user-card {
    margin-bottom: 1rem;
    transition: transform 0.3s ease;
    padding: 0.8rem;
    .user-info {
        flex: 1;
        min-width: 0;
    }
    .agent-id {
        font-size: 0.9rem;
        color: #888;
    }
    &.is-self {
        background: rgba(76, 175, 80, 0.05);
        border: 1px solid #af4ca3;
        box-shadow: 0 0 15px rgba(76, 175, 80, 0.3);
    }
    .agent-name {
        color: #4caf50;
        text-shadow: 0 0 10px rgba(76, 175, 80, 0.6);
        font-size: 0.95rem;
        display: flex;
        align-items: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
.user-card:hover {
    transform: translateX(5px);
}

/* 新增滚动条样式 */
::-webkit-scrollbar {
    width: 8px;
}

::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.2);
}

::-webkit-scrollbar-thumb {
    background: #4caf50;
    border-radius: 4px;
}
.self-icon {
    color: #4caf50;
    margin-left: 8px;
    filter: drop-shadow(0 0 3px #4caf50);
    position: relative;
}

.user-card.active {
    .hologram-avatar {
        filter: grayscale(0) contrast(1.4);
    }
    .neon-border {
        background: conic-gradient(from 0deg, #00ffff 0%, #4caf50 50%, #7028e4 100%);
        animation-duration: 1.5s;
    }
}

.avatar-frame {
    position: relative;
    margin-right: 1rem;
    width: 48px;
    height: 48px;
}
/* 聊天窗口头像尺寸调整 */
.target-avatar {
    width: 56px;
    height: 56px;
    border-radius: 50%;
    border: 2px solid #4caf50;
    box-shadow: 0 0 15px rgba(76, 175, 80, 0.6);
    margin-right: 1.5rem;
}
.hologram-avatar {
    width: 40px;
    /* 实际显示尺寸 */
    height: 40px;
    border-radius: 50%;
    filter: grayscale(0.3) contrast(1.2);
    position: absolute;
    left: 4px;
    top: 4px;
    z-index: 2;
}

/* 优化后的头像样式 */
.avatar-frame {
    position: relative;
    margin-right: 1rem;
    width: 48px;
    height: 48px;
}

/* 全息头像尺寸优化 */
.hologram-avatar {
    width: 40px; /* 实际显示尺寸 */
    height: 40px;
    border-radius: 50%;
    filter: grayscale(0.3) contrast(1.2);
    position: absolute;
    left: 4px;
    top: 4px;
    z-index: 2;
}

/* 霓虹边框重制 */
.neon-border {
    position: absolute;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: conic-gradient(from 0deg, #4caf50 0%, #7028e4 50%, #4caf50 100%);
    animation: borderFlow 3s linear infinite;
    mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    mask-composite: exclude;
    padding: 2px;
}
/* 聊天窗口 */
.cyber-window {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: linear-gradient(160deg, #1a1a1a 0%, #0d0d0d 100%);
    border: 1px solid #7028e4;
    box-shadow: 0 0 40px rgba(112, 40, 228, 0.2), inset 0 0 20px rgba(112, 40, 228, 0.1);
    border-radius: 8px;
    overflow: hidden;

    .target-name {
        font-size: 0.9rem;
        color: #888888;
    }
}
.cyber-button {
    background: linear-gradient(45deg, #7028e4, #4caf50);
    border: 1px solid #00ff87;
    color: white;
    padding: 12px 20px;
    margin-right: 20px;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
}

.button-glitch {
    position: absolute;
    top: -2px;
    left: -2px;
    right: -2px;
    bottom: -2px;
    background: linear-gradient(
        45deg,
        transparent 25%,
        rgba(255, 255, 255, 0.2) 50%,
        transparent 75%
    );
    animation: glitch 2s infinite linear;
}

@keyframes glitch {
    0% {
        transform: translateX(-100%);
    }
    100% {
        transform: translateX(100%);
    }
}

/* 调整标题栏布局 */
.chat-header {
    display: flex;
    align-items: center;
    padding: 15px;
}

.header-glow {
    position: absolute;
    top: -50px;
    left: 50%;
    width: 200%;
    height: 100px;
    background: linear-gradient(
        90deg,
        rgba(112, 40, 228, 0) 0%,
        rgba(112, 40, 228, 0.4) 50%,
        rgba(112, 40, 228, 0) 100%
    );
    animation: headerGlow 6s infinite;
}

/* 消息气泡 */
.message-bubble {
    max-width: 65%;
    padding: 1rem;
    margin: 1rem;
    border-radius: 15px;
    position: relative;
    backdrop-filter: blur(5px);
}

.message-bubble.sent {
    background: linear-gradient(45deg, #4caf50 0%, #2d7a32 100%);
    margin-left: auto;
    box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
}

.message-bubble.received {
    background: linear-gradient(45deg, #7028e4 0%, #4a1e9e 100%);
    box-shadow: 0 5px 15px rgba(112, 40, 228, 0.4);
}

.message-content {
    color: #fff;
    font-size: 1.1rem;
    text-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

/* 输入框 */
.neon-input {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid #4caf50;
    color: #fff;
    padding: 1rem;
    border-radius: 8px;
    transition: all 0.3s ease;
    flex: 1; /* 输入框占据剩余空间 */
    max-width: 85%; /* 限制最大宽度 */
}

.neon-input:focus {
    box-shadow: 0 0 15px #4caf50;
}

.glow-button {
    background: linear-gradient(45deg, #4caf50 0%, #7028e4 100%);
    border: none;
    padding: 1rem 2rem;
    border-radius: 8px;
    position: relative;
    overflow: hidden;
    margin-left: auto; /* 按钮始终靠右 */
    min-width: 100px; /* 固定最小宽度 */
}

.button-rays {
    position: absolute;
    width: 200%;
    height: 100%;
    background: linear-gradient(
        45deg,
        transparent 25%,
        rgba(255, 255, 255, 0.2) 50%,
        transparent 75%
    );
    animation: rays 2s infinite linear;
}

/* 关键帧动画 */
@keyframes neonPulse {
    0%,
    100% {
        opacity: 0.8;
        transform: scale(1);
    }
    50% {
        opacity: 1;
        transform: scale(1.2);
    }
    0% {
        opacity: 0.4;
    }

    50% {
        opacity: 1;
    }

    100% {
        opacity: 0.4;
    }
}

@keyframes borderFlow {
    0% {
        transform: rotate(0deg);
        opacity: 0.8;
    }

    50% {
        opacity: 1;
    }

    100% {
        transform: rotate(360deg);
        opacity: 0.8;
    }
}

@keyframes headerGlow {
    0% {
        transform: translateX(-50%) rotate(0deg);
    }

    100% {
        transform: translateX(-50%) rotate(360deg);
    }
}

@keyframes rays {
    0% {
        transform: translateX(-50%);
    }

    100% {
        transform: translateX(50%);
    }
}
</style>
